/**
 * @author ccpalu
 */
document.title="Loading CNV Browser";

function addDojoScripts(){
/* Dojo needs to be added later because, when reloading a Plot,
 * the url's hash is too big to dojo process, so the fiels are not loaded.
 * First, is necessary read and erase the hash string, then call dojo.

 * Here we are adding dojo scripts and also a JSON, for the browser were 
 * it is not native yet.
 */

	addScript("dojo/dojo.js","scriptdojo"); 

	addScript("dijit/Tooltip.js","scriptdojo"); 
	addScript("dojox/charting/action2d/Base.js","scriptdojo"); 
	addScript("dojox/gfx/_base.js","scriptdojo");
	addScript("dojox/gfx/svg.js","scriptdojo"); 
	
	addScript("dojox/gfx.js","scriptdojo");
	addScript("dojox/charting/action2d/Highlight.js","scriptHigh");
	addScript("dojox/charting/action2d/Magnify.js","scriptHigh");
	addScript("dojox/charting/action2d/Shake.js","scriptHigh");
	addScript("dojox/charting/action2d/Tooltip.js","scriptHigh");
	addScript("dojox/gfx/MoverLimited.js","scriptHigh");


	if (typeof(JSON)=='undefined'){
		addScript("http://cnviewer.googlecode.com/hg/CNViewer/JSON.js");
	}
	addLink("dijit/themes/soria/soria.css","stylesheet");
	
	return false;
}	
			
window.onload = function(){
/* First action. It is necessary to see if any data was submited on the url.
 * If there is anything, it is rea dand removed, to avoid delays do to the big url size.
 */
	var ldiv = document.createElement('div');
	ldiv.id = 'LoadingPageDiv';
	document.body.appendChild(ldiv);
	ldiv.align = 'center';
	var load=document.createElement('IMG');
	load.id='LodingPageText';
	load.src='http://cnviewer.googlecode.com/hg/loading.gif';
	load.width=150;
	load.height=150;
	setPosition(load,0,165);
	load.align = 'center';
	ldiv.appendChild(load);


	if (location.hash){//&&(location.hash>50)){
		var hashes = document.createElement('OBJECT');
		hashes.id = 'hashes';
		
		var pedaco = getUrlVars();
		hashes.cnv = pedaco['variavel1'];//storedInfo[0];
		hashes.opt = pedaco['variavel2'];//storedInfo[1];
		
		location.hash = '';

		document.getElementsByTagName('head')[0].appendChild(hashes);
	}		
	addDojoScripts();
	return false;
};

function loadBrowser(timesTried){
	/* After loading Dojo structures, it is necessary to call some of its functions.
	 * Once they are loaded, all the interface can be created.
	 * This function calls all the necessary functions tu execute the process
	 * above explained.
	 */

	var e= false;
	try	{
		DOJOrequires();	
	}
	catch (e){
		if (timesTried>20){
			alert('We are sorry, the connection with the server is not good at the moment. Please, try again in a few minutes.');
			return false;
		}
		else {
			timesTried=timesTried*1+1;
			setTimeout('loadBrowser(' + timesTried +')',250);
		}
	}
	
	if (!e)	{
		dojoDetails();
		document.title = "Copy Number Variation Browser";
		addLogo();
		loadOptions();
		IntBioinfoButton();
		nameProgram();
		var chartDiv = document.createElement("div");
		chartDiv.id='chartingArea';
		chartDiv.style.zIndex=-150;
		document.body.appendChild(chartDiv);
		parametersMenu();
		remove_element_by_id('LoadingPageDiv');
		var guide = buttonImageA('guide', 'http://cnviewer.googlecode.com/hg/Images/CNViewerGuideLogo.png', CNViewerGuide, 120, 0, 750, 60, 'absolute', 0, 'CNViewer Guide');
		
	}
	return false;
}

function retrieveCNV(){
/* Testing if there is any information on the hash of the URL */
	if (document.getElementById('hashes')) {
		
		return JSON.parse(document.getElementById('hashes').cnv.replace(/'/g, '"'));
	}
	else return false;
}
 
function retrieveSampleList(){
/* If there is any information on the hash, this fucntion will recover
 * the sample list.
 */
	if (document.getElementById('hashes')) {
		var options = document.getElementById('hashes').opt;
		try {
			options = options.replace(/\"/g, "'");
		}
		catch(e){
			console.log('e1 '+  e);
		};
		try {
			options = options.replace(/optionvalue/g, "option value");
		}
		catch(e){
			consle.log('e2 ' + e);
		};

		return options;
	}
	else return false;
}

function cnvObject(){
/* Creates an object were all CNV related vlaues and variables will be stored.
 */
	var cnv = document.createElement('OBJECT');
	cnv.id = 'CNV';
	var retrieveData = retrieveCNV();

	if (!retrieveCNV()) {
		
		cnv.segData = new Array;
		cnv.xAxis = '';
		cnv.ch = new Array();
		cnv.chRegions = new Array(23);
		for (var i = 1; i <= 22; i = i + 1) {
			cnv.chRegions[i] = new Array();
		}
		cnv.extractedSegData = new Array(23);
		cnv.sampleIndex = 0;
		cnv.mapAnswer = new Array();
		cnv.index = 0;
		cnv.max = new Array(22);
		cnv.min = new Array(22);
		
		for (var i = 1; i <= 22; i = i + 1) {
			cnv.max[i] = 0;
			cnv.min[i] = 90000000000;
		}
		cnv.realSize = chSize();
		cnv.ready = false;
		cnv.uploads = new Array(1);
		cnv.similarity = new Object();
		
		cnv.legends = new Array();
		
		
		cnv.clinical = new Object();
		cnv.clinical.labels = new Array();
		cnv.clinical.index = 0;
		cnv.clinical.upload = false;
		cnv.analysisTitle = '';
	}
	else {
		cnv.segData = retrieveData.segData;
		cnv.xAxis = retrieveData.xAxis;
		cnv.ch = retrieveData.ch;
		cnv.chRegions = retrieveData.chRegions;
		cnv.extractedSegData = retrieveData.extractedSegData;
		cnv.sampleIndex = retrieveData.sampleIndex;
		cnv.mapAnswer = retrieveData.mapAnswer;
		cnv.index = retrieveData.index;
		cnv.max = retrieveData.max;
		cnv.min = retrieveData.min;
		cnv.realSize = retrieveData.realSize;
		cnv.realSize.rate = 525/cnv.realSize[1];
		cnv.ready = retrieveData.ready;
		cnv.uploads = new Array(1);
		cnv.similarity = retrieveData.similarity;
		cnv.legends = retrieveData.legends;	
		cnv.clinical = retrieveData.clinical;
		cnv.analysisTitle = retrieveData.analysisTitle;
	}

	
	document.getElementsByTagName('head')[0].appendChild(cnv);

	graphicAreaVariables();
	if (retrieveData)	{
		configOptions();
		closeConfigBox();
	}

	return false;
}

function chSize(){
	/* Size of chromosome in base pars,
	 * GRCh36 primary reference assembly
	 * http://www.ncbi.nlm.nih.gov/projects/genome/assembly/grc/human/data/index.shtml
	 */
	var realSize= new Array(23);
	realSize[0]=0;//it will contain the total size
	realSize[1] = 247249719;
	realSize[2] = 242951149;
	realSize[3] = 199501827;
	realSize[4] = 191273063;
	realSize[5] = 180857866;
	realSize[6] = 170899992;
	realSize[7] = 158821424;
	realSize[8] = 146274826;
	realSize[9] = 140273252;
	realSize[10] = 135374737;
	realSize[11] = 134452384;
	realSize[12] = 132349534;
	realSize[13] = 114142980;
	realSize[14] = 106368585;
	realSize[15] = 100338915;
	realSize[16] = 88827254;
	realSize[17] = 78774742;
	realSize[18] = 76117153;
	realSize[19] = 63811651;
	realSize[20] = 62435964;
	realSize[21] = 46944323;
	realSize[22] = 49691432;
	realSize.rate = 525/realSize[1];
	
	for (var i=1; i<realSize.length; i=i+1){
		realSize[0]=realSize[0]+realSize[i];
	}
	return realSize;
}

function postRetrieve(){
	createChList();
	document.getElementById('choose_sample').disabled = false;

	createExportForm();
	closeUploadBox();

	var cnv = document.getElementById('CNV');

	if ((cnv.similarity.distance!=undefined)&&(cnv.similarity.distance.length))	{
		document.getElementById('sim_method').value = cnv.similarity.metric[1];
		document.getElementById("choose_sample").value=	cnv.similarity.sample[1];

		if (cnv.similarity.chromosome.length==22){
			document.getElementById('chAll').checked = true;
		}
		for (var i=0; i<cnv.similarity.chromosome.length; i=i+1){
			document.getElementById('ch' + cnv.similarity.chromosome[i]).checked=true;
		}

		distanceChart([cnv.similarity.distance,cnv.similarity.sampleNumber.reverse(),cnv.similarity.sampleName]);
	}
	
	return false;
}

function addLogo(){
	var mdaAnchor=document.createElement('a');
	mdaAnchor.setAttribute('href','http://www.mdanderson.org/');
	mdaAnchor.setAttribute('target','_blank');
	document.getElementsByTagName('body')[0].appendChild(mdaAnchor);
	var mdaLogo=document.createElement('IMG');
	mdaLogo.id='Logo';
	mdaLogo.src='http://cnviewer.googlecode.com/hg/Images/mdacclog.png';
	mdaLogo.width=160;
	mdaLogo.height=80;
	mdaLogo.setAttribute("alt","Link to MDA site");
	mdaLogo.setAttribute("style","cursor:pointer");
	setPosition(mdaLogo,30,25);
	mdaAnchor.appendChild(mdaLogo);
	return false;
}

function IntBioinfoButton(){
	/* Creates a button to link with IBL */
	var a1=document.createElement('a');
	a1.setAttribute('href','http://integrativebioinformatics.org/');
	a1.setAttribute('target','_blank');
	document.getElementsByTagName('body')[0].appendChild(a1);
	
	var intBioinfo=document.createElement('INPUT');
	intBioinfo.type='button';
	intBioinfo.id='BioinfoButton';
	intBioinfo.style.cursor="pointer";
	intBioinfo.style.width="200px";
	intBioinfo.value='Integrative Bioinformatics Lab.';
	setPosition(intBioinfo,10,125);	
	a1.appendChild(intBioinfo);
	
	return false;
}

function nameProgram(){
	/* Add a Title to the Interface */
	/*var programTitle = document.createElement("p");
	programTitle.id="ProgramTitle";
	programTitle.innerHTML="CNViewer";
	setPosition(programTitle,250,55);
	setFont(programTitle,"24px","italic");
	document.body.appendChild(programTitle);
*/
	
	programTitle= document.createElement('IMG');
	programTitle.id='ProgramTitle';
	programTitle.src="http://cnviewer.googlecode.com/hg/Images/CNViewerLogo.png";
	document.body.appendChild(programTitle);
	programTitle.title = 'CNViewer';
	programTitle.alt = 'CNViewer';
	programTitle.style.height="120px";
	setPosition(programTitle,270,20);//250,12);
	
	var programRestriction = document.createElement("DIV");
	programRestriction.id="programRestriction";
	programRestriction.style.width="280px";
	programRestriction.style.height="40px";	
	programRestriction.style.right='40px';
	programRestriction.style.bottom='0px';
	programRestriction.style.position='absolute';
	programRestriction.onmouseover=function (){
		document.getElementById("closeRestriction").style.display='';
		return false;
	};
	programRestriction.onmouseout=function(){
		document.getElementById("closeRestriction").style.display='none';
		return false;
	};
	
	document.body.appendChild(programRestriction);

	var close = document.createElement("p");
	close.id="closeRestriction";
	close.innerHTML=" x ";
	close.left='170px';
	setFont(close,"14px",0,0,'bold');
	close.style.backgroundColor="#AACCFF";
	close.style.width="7px";
	close.style.position='absolute';
	close.onclick= function(){
		remove_element_by_id('programRestriction');
		return false;
	};
	close.style.display='none';
	close.style.cursor="pointer";
	programRestriction.appendChild(close);
	
	var programRestrictionP = document.createElement("p");
	programRestrictionP.id="programRestrictionP";
	programRestrictionP.innerHTML="- all functionalities guaranteed in Firefox -";
	setFont(programRestrictionP,"14px","italic");
	//setPosition(programRestrictionP, 1, 20, 'absolute');
	programRestriction.appendChild(programRestrictionP);
	
	return false;
}

function parametersMenu(){
/* First it creates a fieldset in the form 'parametersForm';
 * this form will show the ID of all patients samples.
 * This informations is obtained as result of the 
 * database calling made in the 'getKey' function.
 */

	var parametersForm=document.createElement('FORM');
	parametersForm.id='parametersForm';
	parametersForm.name='parametersForm';
	document.getElementsByTagName('body')[0].appendChild(parametersForm);

	var parametersFieldset=document.createElement('FIELDSET');
	parametersFieldset.id="Parameters";
	setPosition(parametersFieldset,22,270);
	document.getElementById('parametersForm').appendChild(parametersFieldset);

	var parametersLegend=document.createElement('LEGEND');
	parametersLegend.id="ParametersLegend";
	setFont(parametersLegend,"13px");
	document.getElementById('Parameters').appendChild(parametersLegend).innerHTML="Select Parameters";

	var SelectMethodP=document.createElement('p');
	SelectMethodP.id='SelectMethodP';
	var str = 'Similarity Method: <br><select name="sim_method" id="sim_method" onChange="checkParameters()"></select>';
	SelectMethodP.innerHTML=str;
	setFont(SelectMethodP,"13px");
	parametersFieldset.appendChild(SelectMethodP);

	var SelectMethod=document.getElementById('sim_method');
	SelectMethod.style.width="150px";

	var simOptions=["Probe Weighted Euclidean", "PWD", "Size Weighted Euclidean", "SWD", "Breakpoint Euclidean", "SED"];
	for (var i = 0; i < simOptions.length/2; i++) {
		SelectMethod.options[i] = new Option(simOptions[i*2], simOptions[i*2+1]);
	}

	var selectParameters=document.createElement('p');
	selectParameters.id='SelectParameters';
	str = 'Sample: <br><select name="choose_sample" id="choose_sample" disabled=true onChange="checkParameters()"></select>';
	selectParameters.innerHTML=str;
	setFont(selectParameters,"13px");
	parametersFieldset.appendChild(selectParameters);

	var selectSample=document.getElementById('choose_sample');
	selectSample.style.width="150px";
	selectSample.innerHTML= retrieveSampleList();
	if (!selectSample.innerHTML){
		selectSample.options[0] = new Option(" -- select --", -1);
	}

	var selectChrP=document.createElement('p');
	selectChrP.id='SelectChrP';
	var str = 'Chromosomes';
	selectChrP.innerHTML=str;
	setFont(selectChrP,"13px");
	parametersFieldset.appendChild(selectChrP);
	buttonImage('chOpenMenu', 'http://cnviewer.googlecode.com/hg/Images/arrowD3.png', "chMenu()", 10, 12, 135, -27, "relative", parametersFieldset).title='Click to specify the chromosomes';

	var submitParameters=document.createElement('INPUT');
	submitParameters.type='button';
	submitParameters.id='submitParametersButton';
	submitParameters.onclick=similarity;
	submitParameters.disabled=true;
	submitParameters.value = 'Submit!';
	parametersFieldset.appendChild(submitParameters);
	submitParameters.align.position='right';

	createChMenu();
	if (document.getElementById('hashes'))
	{
	postRetrieve();
	}

	//Help Background
	var hBg = document.createElement('IMG');
	parametersForm.appendChild(hBg);
	hBg.id=hBg;
	hBg.src="http://cnviewer.googlecode.com/hg/Images/intBG.png";
	hBg.style.position="absolute";
	hBg.style.top='262px';
	hBg.style.left='164px';
	
	addHelp ('hParameters', 'help', 'http://sites.google.com/site/cnviewerguide/analysis', 'parametersForm', 270, 170, 12);
	
	return false;
}

function checkParameters(){
	var sample = document.getElementById("choose_sample");
	if (((!sample.disabled)&&(sample.value>=0))&&(chSelected().length>0)){
		document.getElementById("submitParametersButton").disabled=false;
	}
	else{
		document.getElementById("submitParametersButton").disabled=true;
	}
	return false;
}

function createChMenu(){
	var currentP;	
	setFont(createParagraph('chAllP','<input type="checkbox" name = "chAll" id="chAll" onClick="allChCheck(this)"> All </input>', 'Parameters'), '13px');
	for (var i=1; i<=22; i=i+1){
		currentP=createParagraph('ch'+i+'P','<input type="checkbox" name = "ch'+i+'" id="ch'+i+'" onClick="chCheck(this)"> '+i+' </input>', 'Parameters');
		setFont(currentP, '13px');
		currentP.style.width = "50px";
	}
	
	var positionCorrection = 41;
	
	
	switch (window.navigator.appName){
		case 'Opera' :
			positionCorrection = 43;
			var col1=15, col2=70, col3=120;
			break;
		default:
			var col1=0, col2=60, col3=110;	
	}
	
	var varDist=-24;
	
	var posit = 160;
	setPosition("chAllP", col1, posit,"absolute");
	setPosition("ch1P", col3, posit,"absolute");

	for (var i=2; i<=22; i=i+3){
		setPosition("ch"+i+"P", col1, posit+((i+1)/3)*20, "absolute");
		setPosition("ch"+(i+1)+"P", col2, posit+((i+1)/3)*20,"absolute");
		setPosition("ch"+(2+i)+"P",col3, posit+((i+1)/3)*20,"absolute");
	}
	var chPosB = buttonImage('chListButton', 'http://cnviewer.googlecode.com/hg/Images/chPositionDisab.png', 'chListVisibility()', 26, 150, 197, 373).disable=true;
	chPosB.title = "Select chromosomes' especific regions";

	chMenu();

	return false;
}

function chMenu(){
	if (document.getElementById('chAllP').style.display == "none") {
		document.getElementById('chOpenMenuImg').src = 'http://cnviewer.googlecode.com/hg/Images/arrowD6.png';
		document.getElementById('chAllP').style.display="";
		document.getElementById('chListButton').style.display="";
		document.getElementById('chOpenMenu').title='Hide chromosome list';
		
		for (var i = 1; i <= 22; i = i + 1) {
			document.getElementById('ch'+i+'P').style.display="";
		}

			
		var h = 330;
		
	}
	else{
		document.getElementById('chListButton').style.display="none";
		document.getElementById('chOpenMenuImg').src = 'http://cnviewer.googlecode.com/hg/Images/arrowD3.png';
		document.getElementById('chAllP').style.display="none";
		document.getElementById('chOpenMenu').title='Click to specify the chromosomes';
		for (var i = 1; i <= 22; i = i + 1) {
			document.getElementById('ch'+i+'P').style.display="none";
		}

		try {
			if (document.getElementById('chList').visible)
				chListVisibility();
		}
		catch(e){}
		
		var h = 160;

	}
	
	document.getElementById('Parameters').style.height = (13+h)+"px";

		setPosition('submitParametersButton', 82, h);

	try {
		setPosition("HB", 0, h + 305);
	}
	catch(temp){};
		
	return false;
}

function allChCheck(allCheck){
	if (allCheck.checked)
		var value = true;
	else
		var value = false;

	for (var i=1;i<=22;i=i+1){
		document.getElementById('ch'+i).checked = value;
	}
	
	checkParameters();
	
	return false;
}

function chCheck(ch){
	if (!ch.checked)
		document.getElementById('chAll').checked = false;
	checkParameters();
	
	return false;
}

function chSelected(){
	
	var chList = new Array();
	for (var i=1,j=0; i<=22; i=i+1){
		if (document.getElementById('ch' + i).checked) {
			chList[j] = i;
			j=j+1;
		}
	}
	document.getElementById('CNV').ch = chList;
	
	return chList;
}

function CNViewerGuide(){
	
	var gbPopup = window.open('http://sites.google.com/site/cnviewerguide/home');

		//Checking if the pop-up blocker is disabled
		if (gbPopup == null || typeof(gbPopup) == 'undefined'){
			alert ('Please disable your pop-up blocker and click at the "UCSC Genome Browser" again.');
		}
		else{
			gbPopup.focus();
		}

		return false;
}
function dojoDetails(){
	
	var node1 = document.createElement("div");
	document.body.appendChild(node1);
	node1.style.zIndex=(-2)*500;
	node1.style.width = "850px";
	node1.style.height = "850px";
	node1.style.top = "5px";
	node1.style.left = "5px";
	node1.style.position = "absolute";
	
	var surfaceHeight = 700;
	var surfaceWidth = 700;
	var surface = dojox.gfx.createSurface(node1, surfaceWidth, surfaceHeight);
	
	var rect1 = {
	x: 0,
	y: 0,
	width: 206,
	height: 700,
	r: 10
	};
	var lg1 = {
		type: "linear",
		x1: 0,
		y1: 0,
		x2: 100,
		y2: 600,
		colors: [{
			offset: 0,
			color: "rgba(60,180,0,0.6)"
		}, {
			offset: 1,
			color: "rgba(255,180,255,0)"
		}]
	};
	
	// this is an example to split the linearGradient from setFill:
	var rect2 = {
		x: 0,
		y: 0,
		width: 500,//600,
		height: 150,
		r: 10
	};
	
	var lg2 = {
		type: "linear",
		x1: 0,
		y1: 0,
		x2: 470,//550,
		y2: 120,//150,
		colors: [{
			offset: 0,
			color: "rgba(255,255,27,0.4)"
		},  //					{ offset: 0.5, color: "rgba(30,120,240,0.4)"},
		{
			offset: 0.6,
			color: "rgba(30,120,240,0.4)"//"rgba(48,96,144,0.4)"
		}, {
			offset: 1,
			color: "#23242C"//"rgba(48,96,144,0.4)"
		}]
	};
	
	var vDetail = surface.createRect(rect1).setFill(lg1).setTransform({
		dx: 3,
		dy: 0
	});
	
	var hDetail = surface.createRect(rect2).setFill(lg2).setTransform({
			dx: 3,
			dy: 0
	});
	hDetail.getEventSource().setAttribute('id','hRectDetail');
	vDetail.getEventSource().setAttribute('id','vRectDetail');
	return false;
}
